package com.cskaoyan.service.wx_cart;

import com.cskaoyan.bean.goods.Goods;
import com.cskaoyan.bean.goods.GoodsExample;
import com.cskaoyan.bean.goods.GoodsProduct;
import com.cskaoyan.bean.goods.GoodsProductExample;
import com.cskaoyan.bean.promote.Coupon;
import com.cskaoyan.bean.promote.CouponUser;
import com.cskaoyan.bean.user.Address;
import com.cskaoyan.bean.user.AddressExample;
import com.cskaoyan.bean.wx_address.AddressVO;
import com.cskaoyan.bean.wx_cart.*;
import com.cskaoyan.bean.wx_cart.bo.FastAddBO;
import com.cskaoyan.bean.wx_order_before.vo.GoodsListBean;
import com.cskaoyan.mapper.configmanagement.ConfigManagementMapper;
import com.cskaoyan.mapper.goods.GoodsMapper;
import com.cskaoyan.mapper.goods.GoodsProductMapper;
import com.cskaoyan.mapper.promote.CouponMapper;
import com.cskaoyan.mapper.promote.CouponUserMapper;
import com.cskaoyan.mapper.user.AddressMapper;
import com.cskaoyan.mapper.wx_cart.CartMapper;
import com.cskaoyan.service.wx_address.WxAddressService;
import com.cskaoyan.service.wx_coupon.WxCouponService;
import com.cskaoyan.utils.Constant;
import com.cskaoyan.utils.ReflectionSetJavaBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

@Repository
public class WxCartServiceImpl implements WxCartService {
    @Resource
    CartMapper cartMapper;

    @Resource
    GoodsMapper goodsMapper;
    @Resource
    CouponMapper couponMapper;
    @Resource
    ConfigManagementMapper configManagementMapper;
    @Resource
    GoodsProductMapper goodsProductMapper;
    @Autowired
    WxAddressService wxAddressService;
    @Autowired
    WxCouponService wxCouponService;


    @Override
    public List<Cart> updateCartChecked(CartBO cartBO) {
        List<Integer> list = Arrays.asList(cartBO.getProductIds());
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andUserIdEqualTo(cartBO.getUserId());
        criteria.andProductIdIn(list);
        Cart cart = new Cart();
        cart.setChecked(cartBO.getIsChecked() == 1);
        if (cartBO.getIsChecked() == 1) cart.setChecked(true);
        int i = cartMapper.updateByExampleSelective(cart, cartExample);
        return queryCartByUserId(cartBO.getUserId());
    }

    @Override
    public List<Cart> deleteCartInfo(CartBO cartBO) {
        Cart cart = new Cart();
        ReflectionSetJavaBeanUtils.setBeanDeletedValue(cart);
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        List<Integer> list = Arrays.asList(cartBO.getProductIds());
        criteria.andProductIdIn(list);
        criteria.andUserIdEqualTo(cartBO.getUserId());
        int i = cartMapper.updateByExampleSelective(cart, cartExample);
        return queryCartByUserId(cartBO.getUserId());
    }

    //创建购物车表即可
    @Override
    public int fastAdd(FastAddBO fastAddBO) {
        //如果林锟没有写商品相同就合并的话，这段代码要去掉
        CartExample cartExample = new CartExample();
        CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        cartExampleCriteria.andDeletedEqualTo(false);
        cartExampleCriteria.andGoodsIdEqualTo(fastAddBO.getGoodsId());
        cartExampleCriteria.andProductIdEqualTo(fastAddBO.getProductId());
        List<Cart> carts = cartMapper.selectByExample(cartExample);
        if (carts.size() != 0) {
            Cart cart = carts.get(0);
            cart.setNumber((short) (cart.getNumber() + fastAddBO.getNumber()));
            cartMapper.updateByPrimaryKeySelective(cart);
            return Constant.SUCCESS;
        }
        Integer userId = fastAddBO.getUserId();
        Goods goods = goodsMapper.selectByPrimaryKey(fastAddBO.getGoodsId());
        GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(fastAddBO.getProductId());
        Cart cart = new Cart();
        ReflectionSetJavaBeanUtils.setJavaBean(cart);
        cart.setUserId(userId);
        cart.setGoodsId(goods.getId());
        cart.setChecked(true);
        cart.setGoodsName(goods.getName());
        cart.setGoodsSn(goods.getGoodsSn());
        cart.setProductId(fastAddBO.getProductId());
        cart.setNumber((short) (int) fastAddBO.getNumber());
        cart.setSpecifications(goodsProduct.getSpecifications());
        cart.setPrice(goodsProduct.getPrice());
        cart.setChecked(true);
        cart.setPicUrl(goodsProduct.getUrl());
        cartMapper.insertSelective(cart);
        return cart.getId();
    }


    public CheckoutVO checkout(CheckoutBO checkoutBO) {
        //判断是否存在默认地址
        AddressVO addressVO = wxAddressService.queryAddressDetail(checkoutBO.getAddressId());
        if (checkoutBO.getAddressId() == 0) {
            List<AddressVO> addressVOS = wxAddressService.queryAddressByUserId(checkoutBO.getUserId());
            for (AddressVO vo : addressVOS) {
                if (vo.isIsDefault()) addressVO = vo;
            }
        }
        //取出用户选中的商品(cart中)
        CartExample cartExample = new CartExample();
        CartExample.Criteria cartExampleCriteria = cartExample.createCriteria();
        if (checkoutBO.getCartId() == 0) {
            cartExampleCriteria.andUserIdEqualTo(checkoutBO.getUserId());
            cartExampleCriteria.andCheckedEqualTo(true);
            cartExampleCriteria.andDeletedEqualTo(false);
            cartExampleCriteria.andDeletedEqualTo(false);
        } else {
            cartExampleCriteria.andIdEqualTo(checkoutBO.getCartId());
        }
        List<Cart> carts = cartMapper.selectByExample(cartExample);

        BigDecimal goodsTotalPrice = new BigDecimal(0);
        BigDecimal OrderTotalPrice = new BigDecimal(0);
//       LinkedList<Integer> goodsProductIdList = new LinkedList<>();
        for (Cart cart : carts) {
//            goodsProductIdList.add(cart.getProductId());
            goodsTotalPrice = goodsTotalPrice.add(cart.getPrice().multiply(new BigDecimal(cart.getNumber())));
        }
//        GoodsProductExample goodsProductExample = new GoodsProductExample();
//        GoodsProductExample.Criteria criteria = goodsProductExample.createCriteria();
//        criteria.andIdIn(goodsProductIdList);
//        criteria.andDeletedEqualTo(false);
//        List<GoodsProduct> goodsProducts = goodsProductMapper.selectByExample(goodsProductExample);
//        if (goodsProducts.size() != carts.size()) {
//            return null;
//        }

        //查找优惠金额
        BigDecimal discount = new BigDecimal(0);
//        if (checkoutBO.getUserCouponId() > 0) {
//            CouponUser couponUser = couponUserMapper.selectByPrimaryKey(checkoutBO.getUserCouponId());
//            Coupon coupon = couponMapper.selectByPrimaryKey(couponUser.getCouponId());
//            discount = coupon.getDiscount();
//        }
        if (checkoutBO.getCouponId() > 0) {
            Coupon coupon = couponMapper.selectByPrimaryKey(checkoutBO.getCouponId());
            discount = coupon.getDiscount();
        } else {

        }
        //是否需要邮费
        String freightMin = configManagementMapper.selectByName("market_express_freight_min");
        String freightValue = configManagementMapper.selectByName("market_express_freight_value");
        BigDecimal freight = new BigDecimal(freightValue);
        if (goodsTotalPrice.subtract(discount).compareTo(new BigDecimal(0)) >= 0)
            OrderTotalPrice = goodsTotalPrice.subtract(discount);
        if (new BigDecimal(freightMin).compareTo(OrderTotalPrice) <= 0) freight = new BigDecimal(0);


        //查团购优惠0,0
        CheckoutVO checkoutVO = new CheckoutVO();
        checkoutVO.setCheckedGoodsList(carts);
        checkoutVO.setCheckedAddress(addressVO);
        checkoutVO.setCartId(carts.size() == 1 ? carts.get(0).getId() : 0);
        checkoutVO.setUserCouponId(checkoutBO.getUserCouponId());

        //可用优惠券的张数，调接口
        checkoutVO.setAvailableCouponLength(wxCouponService.queryMyAvailableCoupon1(checkoutBO.getCartId(), 0).size());
        checkoutVO.setFreightPrice(freight);
        checkoutVO.setCouponPrice(discount);

        //暂时先传orderPrice
        checkoutVO.setGoodsTotalPrice(goodsTotalPrice);
        checkoutVO.setOrderTotalPrice(OrderTotalPrice);
        checkoutVO.setGrouponPrice(new BigDecimal(0));
        checkoutVO.setGrouponRulesId(0);
        checkoutVO.setActualPrice(OrderTotalPrice.add(freight));
        checkoutVO.setCouponId(checkoutBO.getCouponId());
        if (addressVO != null) {
            checkoutVO.setAddressId(addressVO.getId());
        }

        return checkoutVO;
    }

    /**
     * 按照userId查询cart
     *
     * @param userId
     * @return
     */
    private List<Cart> queryCartByUserId(Integer userId) {
        CartExample cartExample = new CartExample();
        CartExample.Criteria criteria = cartExample.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andUserIdEqualTo(userId);
        return cartMapper.selectByExample(cartExample);
    }

}
